package com.li.configserve.config.es;

import com.li.configserve.domain.properties.EsProperties;
import com.li.toolkit.constant.LogConst;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author MarLonBrando
 */
@Configuration
public class BaseElasticConfig {

    private final Logger logger = LoggerFactory.getLogger(BaseElasticConfig.class);

    @Autowired
    private EsProperties esProperties;

    @Bean
    public RestHighLevelClient esRestClient() {
        try {
            /*1.设置请求头，避免每个请求都必须指定*/
            /**Header[] defaultHeaders = new Header[]{
                    new BasicHeader("password", "value")
            };**/
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(
                            //在这里配置你的elasticsearch的情况
                            new HttpHost(esProperties.getHost(), Integer.parseInt(esProperties.getPort()), "http")
                    )
            );

            logger.info(LogConst.LOG_SUCCESS_PREFIX + "Es初始化完成...");
            return client;
        }catch (Exception e){
            logger.info(LogConst.LOG_FAILURE_PREFIX+e.getMessage());
            return null;
        }
    }

}
